<template>
  <!-- 新增编辑弹框 -->
  <a-modal
    :width="700"
    :maskClosable="false"
    :visible="props.visible"
    :confirm-loading="loading"
    :forceRender="true"
    :title="isUpdate ? '编辑进场煤分摊记录' : '新建进场煤分摊记录'"
    :body-style="{ paddingBottom: '8px', height: '500px', overflowY: 'auto' }"
    @update:visible="updateVisible"
    @ok="save"
    @close="updateVisible(false)">
    <pr-weight-recods-form v-model:form="form" ref="prWeightRecodsFormRef" :prWeightSumOrderList="prWeightSumOrderList" :managerCodeList="managerCodeList" :layerCodeList="layerCodeList"  @addRecord="toAddRecord" @deleteRecord="toDeleteRecord" @changewtSumId="toChangewtSumId"/>
  </a-modal>
</template>

<script setup name="PrWeightRecodsAddEdit">
import { ref, onMounted, watch } from 'vue';
import PrWeightRecodsForm from './pr-weight-recods-form.vue';
import { message } from 'ant-design-vue';
import { PrWeightRecodsApi } from '../api/PrWeightRecodsApi';
import { WmMdWarehouseManageApi } from '@/views/biz/base/wm-md-warehouse-manage/api/WmMdWarehouseManageApi';
import { WmMdLayerApi } from '@/views/biz/base/wm-md-layer/api/WmMdLayerApi';
import { PrWeightSumOrderApi } from '@/views/biz/interface/pr-weight-sum-order/api/PrWeightSumOrderApi';


const props = defineProps({
  visible: Boolean,
  data: Object
});


const emits = defineEmits(['update:visible', 'done']);

// 弹框加载
const loading = ref(false);

// 是否是编辑状态
const isUpdate = ref(false);

// ref
const prWeightRecodsFormRef = ref(null);

onMounted(() => {
  if (props.data) {
    isUpdate.value = true;
    getDetail();
  } else {
    isUpdate.value = false;
  }
  callchildrenMethod();

});

// 获取详情
const getDetail = () => {
  PrWeightRecodsApi.detail({ pwrId: props.data.pwrId }).then(res => {
    form.value = Object.assign({}, res);
  });
};



// 更改弹框状态 
const updateVisible = value => {
  emits('update:visible', value);
};

// 点击保存
const save = async () => {
 // console.log('入堆重量:', form.value.coalQuantitys[0].inWeight);
  prWeightRecodsFormRef.value.$refs.formRef.validate().then(async valid => {
    if (valid) {
      // 修改加载框为正在加载
      loading.value = true;

      let result = null;

      // 执行编辑或修改
      if (isUpdate.value) {
        result = PrWeightRecodsApi.edit(form.value);
      } else {
        result = PrWeightRecodsApi.add(form.value);
      }
      result
        .then(async result => {
          // 移除加载框
          loading.value = false;

          // 提示添加成功
          message.success(result.message);

          // 关闭弹框，通过控制visible的值，传递给父组件
          updateVisible(false);

          // 触发父组件done事件
          emits('done');
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
};

//=============================子组件===========================================

// 表单数据
const form = ref({
  weight:0,
  forecastQnetar:0,
  forecastStd:0,
  notdidWeight:0, //未分配
  didWeight:0, //已分配
  coalQuantitys:[], //分摊煤量
});

// 煤场列表初始化
const prWeightSumOrderList= ref([]);
const managerCodeList = ref([]);
const layerCodeList = ref([]);



// 按钮 获取子组件新增
const toAddRecord = (data)=>{
  form.value.coalQuantitys.push(data)
}

const toDeleteRecord = (index)=>{
  //按钮 进行删除操作
  form.value.coalQuantitys.splice(index,1)
}
const callchildrenMethod =()=>{
  getPrWeightSoAttributes();
  getManagerCodeAttributes();
  getLayerCodeAttributes();

}

/**
 *下拉列表 获取所有的进厂煤列表数据
 * @author fengshuonan
 * @date 2021/12/29 10:08:31
 */
 const getPrWeightSoAttributes = async () => {
  let templates = await PrWeightSumOrderApi.findList();
  prWeightSumOrderList.value = [];
  for (let template of templates) {
    if (template.delFlag === 'N') {
      prWeightSumOrderList.value.push({
        value: template.wsoId,
        label: template.wtSumId
      });
    }
  }
};

/**
 *下拉列表  获取所有的煤场区域代码
 *
 * @author fengshuonan
 * @date 2021/12/29 10:08:31
 */
 const getManagerCodeAttributes = async () => {
  let templates = await WmMdWarehouseManageApi.findList();
  managerCodeList.value = [];
  for (let template of templates) {
    if (template.delFlag === 'N') {
      managerCodeList.value.push({
        value: template.managerCode,
        label: template.managerName
      });
    }
  }
};

/**
 *下拉列表  获取所有的煤场区域层高代码
 *
 * @author fengshuonan
 * @date 2021/12/29 10:08:31
 */
 const getLayerCodeAttributes = async () => {
  let templates = await WmMdLayerApi.findList();
  layerCodeList.value = [];
  for (let template of templates) {
    if (template.delFlag === 'N') {
      layerCodeList.value.push({
        value: template.layerCode,
        label: template.layerName
      });
    }
  }
};



/**
 * 触发事件  汇总单号变更后，得到详情
 *
 * @author fengshuonan
 * @date 2021/12/29 10:08:31
 */
const toChangewtSumId =async(value)=>{
  restChildItem();
  console.log("changewtSumId:"+value);
  let templates = await PrWeightSumOrderApi.detail({ wsoId: value });
    if (templates && Object.keys(templates).length > 0) {
      form.value.weight=templates.weight;
      // 默认未分配的为汇总重量
      form.value.notdidWeight = templates.weight;
      form.value.forecastStd = templates.forecastStd;
      form.value.forecastQnetar = templates.forecastQnetar;
     }
}

//变更化初始化下拉列表状态，必须要清除下列内容
const restChildItem=()=>{
  form.value.weight=0;
  form.value.notdidWeight=0;
  form.value.didWeight=0;
  form.value.coalQuantitys=[];
}


//监听   监听未分量和已分量变化
watch(
  () => form.value.coalQuantitys,
  ([newValue]) => {
    if (newValue && form.value.weight != null) { // 确保汇总重量有值且不是null
      let didWeight = 0;
      for (let i = 0; i < form.value.coalQuantitys.length; i++) {
        const inWeight = form.value.coalQuantitys[i]['inWeight'];
        if (inWeight) { // 判断入堆量是否有值
          didWeight += Number(inWeight);
        }
      }
      form.value.didWeight = didWeight;
      //form.value.notdidWeight = Math.max(form.value.weight - didWeight, 0); // 确保未分配量非负数
      form.value.notdidWeight = form.value.weight - didWeight; // 确保未分配量非负数
    }
  },
  { deep: true } // 深度监听数组内容
);


</script>

<style></style>
